
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Migration Operations &#8212; Django 1.11.22.dev20190603194737 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="Models" href="models/index.html" />
    <link rel="prev" title="Middleware" href="middleware.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.11.22.dev20190603194737 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="models/index.html" title="Models">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-migration-operations">
            
  <div class="section" id="s-module-django.db.migrations.operations">
<span id="s-migration-operations"></span><span id="module-django.db.migrations.operations"></span><span id="migration-operations"></span><h1>Migration Operations<a class="headerlink" href="#module-django.db.migrations.operations" title="Permalink to this headline">¶</a></h1>
<p>Migration files are composed of one or more <code class="docutils literal notranslate"><span class="pre">Operation</span></code>s, objects that
declaratively record what the migration should do to your database.</p>
<p>Django also uses these <code class="docutils literal notranslate"><span class="pre">Operation</span></code> objects to work out what your models
looked like historically, and to calculate what changes you’ve made to
your models since the last migration so it can automatically write
your migrations; that’s why they’re declarative, as it means Django can
easily load them all into memory and run through them without touching
the database to work out what your project should look like.</p>
<p>There are also more specialized <code class="docutils literal notranslate"><span class="pre">Operation</span></code> objects which are for things like
<a class="reference internal" href="../topics/migrations.html#data-migrations"><span class="std std-ref">data migrations</span></a> and for advanced manual database
manipulation. You can also write your own <code class="docutils literal notranslate"><span class="pre">Operation</span></code> classes if you want
to encapsulate a custom change you commonly make.</p>
<p>If you need an empty migration file to write your own <code class="docutils literal notranslate"><span class="pre">Operation</span></code> objects
into, just use <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">makemigrations</span> <span class="pre">--empty</span> <span class="pre">yourappname</span></code>,
but be aware that manually adding schema-altering operations can confuse the
migration autodetector and make resulting runs of <a class="reference internal" href="django-admin.html#django-admin-makemigrations"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">makemigrations</span></code></a>
output incorrect code.</p>
<p>All of the core Django operations are available from the
<code class="docutils literal notranslate"><span class="pre">django.db.migrations.operations</span></code> module.</p>
<p>For introductory material, see the <a class="reference internal" href="../topics/migrations.html"><span class="doc">migrations topic guide</span></a>.</p>
<div class="section" id="s-schema-operations">
<span id="schema-operations"></span><h2>Schema Operations<a class="headerlink" href="#schema-operations" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-createmodel">
<span id="createmodel"></span><h3><code class="docutils literal notranslate"><span class="pre">CreateModel</span></code><a class="headerlink" href="#createmodel" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.CreateModel">
<em class="property">class </em><code class="descname">CreateModel</code>(<em>name</em>, <em>fields</em>, <em>options=None</em>, <em>bases=None</em>, <em>managers=None</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#CreateModel"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.CreateModel" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Creates a new model in the project history and a corresponding table in the
database to match it.</p>
<p><code class="docutils literal notranslate"><span class="pre">name</span></code> is the model name, as would be written in the <code class="docutils literal notranslate"><span class="pre">models.py</span></code> file.</p>
<p><code class="docutils literal notranslate"><span class="pre">fields</span></code> is a list of 2-tuples of <code class="docutils literal notranslate"><span class="pre">(field_name,</span> <span class="pre">field_instance)</span></code>.
The field instance should be an unbound field (so just
<code class="docutils literal notranslate"><span class="pre">models.CharField(...)</span></code>, rather than a field taken from another model).</p>
<p><code class="docutils literal notranslate"><span class="pre">options</span></code> is an optional dictionary of values from the model’s <code class="docutils literal notranslate"><span class="pre">Meta</span></code> class.</p>
<p><code class="docutils literal notranslate"><span class="pre">bases</span></code> is an optional list of other classes to have this model inherit from;
it can contain both class objects as well as strings in the format
<code class="docutils literal notranslate"><span class="pre">&quot;appname.ModelName&quot;</span></code> if you want to depend on another model (so you inherit
from the historical version). If it’s not supplied, it defaults to just
inheriting from the standard <code class="docutils literal notranslate"><span class="pre">models.Model</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">managers</span></code> takes a list of 2-tuples of <code class="docutils literal notranslate"><span class="pre">(manager_name,</span> <span class="pre">manager_instance)</span></code>.
The first manager in the list will be the default manager for this model during
migrations.</p>
</div>
<div class="section" id="s-deletemodel">
<span id="deletemodel"></span><h3><code class="docutils literal notranslate"><span class="pre">DeleteModel</span></code><a class="headerlink" href="#deletemodel" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.DeleteModel">
<em class="property">class </em><code class="descname">DeleteModel</code>(<em>name</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#DeleteModel"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.DeleteModel" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Deletes the model from the project history and its table from the database.</p>
</div>
<div class="section" id="s-renamemodel">
<span id="renamemodel"></span><h3><code class="docutils literal notranslate"><span class="pre">RenameModel</span></code><a class="headerlink" href="#renamemodel" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RenameModel">
<em class="property">class </em><code class="descname">RenameModel</code>(<em>old_name</em>, <em>new_name</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#RenameModel"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RenameModel" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Renames the model from an old name to a new one.</p>
<p>You may have to manually add
this if you change the model’s name and quite a few of its fields at once; to
the autodetector, this will look like you deleted a model with the old name
and added a new one with a different name, and the migration it creates will
lose any data in the old table.</p>
</div>
<div class="section" id="s-altermodeltable">
<span id="altermodeltable"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterModelTable</span></code><a class="headerlink" href="#altermodeltable" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterModelTable">
<em class="property">class </em><code class="descname">AlterModelTable</code>(<em>name</em>, <em>table</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterModelTable"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterModelTable" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Changes the model’s table name (the <a class="reference internal" href="models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_table</span></code></a>
option on the <code class="docutils literal notranslate"><span class="pre">Meta</span></code> subclass).</p>
</div>
<div class="section" id="s-alteruniquetogether">
<span id="alteruniquetogether"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterUniqueTogether</span></code><a class="headerlink" href="#alteruniquetogether" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterUniqueTogether">
<em class="property">class </em><code class="descname">AlterUniqueTogether</code>(<em>name</em>, <em>unique_together</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterUniqueTogether"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterUniqueTogether" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Changes the model’s set of unique constraints (the
<a class="reference internal" href="models/options.html#django.db.models.Options.unique_together" title="django.db.models.Options.unique_together"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_together</span></code></a> option on the <code class="docutils literal notranslate"><span class="pre">Meta</span></code>
subclass).</p>
</div>
<div class="section" id="s-alterindextogether">
<span id="alterindextogether"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterIndexTogether</span></code><a class="headerlink" href="#alterindextogether" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterIndexTogether">
<em class="property">class </em><code class="descname">AlterIndexTogether</code>(<em>name</em>, <em>index_together</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterIndexTogether"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterIndexTogether" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Changes the model’s set of custom indexes (the
<a class="reference internal" href="models/options.html#django.db.models.Options.index_together" title="django.db.models.Options.index_together"><code class="xref py py-attr docutils literal notranslate"><span class="pre">index_together</span></code></a> option on the <code class="docutils literal notranslate"><span class="pre">Meta</span></code>
subclass).</p>
</div>
<div class="section" id="s-alterorderwithrespectto">
<span id="alterorderwithrespectto"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterOrderWithRespectTo</span></code><a class="headerlink" href="#alterorderwithrespectto" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterOrderWithRespectTo">
<em class="property">class </em><code class="descname">AlterOrderWithRespectTo</code>(<em>name</em>, <em>order_with_respect_to</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterOrderWithRespectTo"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterOrderWithRespectTo" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Makes or deletes the <code class="docutils literal notranslate"><span class="pre">_order</span></code> column needed for the
<a class="reference internal" href="models/options.html#django.db.models.Options.order_with_respect_to" title="django.db.models.Options.order_with_respect_to"><code class="xref py py-attr docutils literal notranslate"><span class="pre">order_with_respect_to</span></code></a> option on the <code class="docutils literal notranslate"><span class="pre">Meta</span></code>
subclass.</p>
</div>
<div class="section" id="s-altermodeloptions">
<span id="altermodeloptions"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterModelOptions</span></code><a class="headerlink" href="#altermodeloptions" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterModelOptions">
<em class="property">class </em><code class="descname">AlterModelOptions</code>(<em>name</em>, <em>options</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterModelOptions"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterModelOptions" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Stores changes to miscellaneous model options (settings on a model’s <code class="docutils literal notranslate"><span class="pre">Meta</span></code>)
like <code class="docutils literal notranslate"><span class="pre">permissions</span></code> and <code class="docutils literal notranslate"><span class="pre">verbose_name</span></code>. Does not affect the database, but
persists these changes for <a class="reference internal" href="#django.db.migrations.operations.RunPython" title="django.db.migrations.operations.RunPython"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunPython</span></code></a> instances to use. <code class="docutils literal notranslate"><span class="pre">options</span></code>
should be a dictionary mapping option names to values.</p>
</div>
<div class="section" id="s-altermodelmanagers">
<span id="altermodelmanagers"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterModelManagers</span></code><a class="headerlink" href="#altermodelmanagers" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterModelManagers">
<em class="property">class </em><code class="descname">AlterModelManagers</code>(<em>name</em>, <em>managers</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AlterModelManagers"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterModelManagers" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Alters the managers that are available during migrations.</p>
</div>
<div class="section" id="s-addfield">
<span id="addfield"></span><h3><code class="docutils literal notranslate"><span class="pre">AddField</span></code><a class="headerlink" href="#addfield" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AddField">
<em class="property">class </em><code class="descname">AddField</code>(<em>model_name</em>, <em>name</em>, <em>field</em>, <em>preserve_default=True</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/fields.html#AddField"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AddField" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Adds a field to a model. <code class="docutils literal notranslate"><span class="pre">model_name</span></code> is the model’s name, <code class="docutils literal notranslate"><span class="pre">name</span></code> is
the field’s name, and <code class="docutils literal notranslate"><span class="pre">field</span></code> is an unbound Field instance (the thing
you would put in the field declaration in <code class="docutils literal notranslate"><span class="pre">models.py</span></code> - for example,
<code class="docutils literal notranslate"><span class="pre">models.IntegerField(null=True)</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">preserve_default</span></code> argument indicates whether the field’s default
value is permanent and should be baked into the project state (<code class="docutils literal notranslate"><span class="pre">True</span></code>),
or if it is temporary and just for this migration (<code class="docutils literal notranslate"><span class="pre">False</span></code>) - usually
because the migration is adding a non-nullable field to a table and needs
a default value to put into existing rows. It does not affect the behavior
of setting defaults in the database directly - Django never sets database
defaults and always applies them in the Django ORM code.</p>
</div>
<div class="section" id="s-removefield">
<span id="removefield"></span><h3><code class="docutils literal notranslate"><span class="pre">RemoveField</span></code><a class="headerlink" href="#removefield" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RemoveField">
<em class="property">class </em><code class="descname">RemoveField</code>(<em>model_name</em>, <em>name</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/fields.html#RemoveField"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RemoveField" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Removes a field from a model.</p>
<p>Bear in mind that when reversed, this is actually adding a field to a model.
The operation is reversible (apart from any data loss, which of course is
irreversible) if the field is nullable or if it has a default value that can be
used to populate the recreated column. If the field is not nullable and does
not have a default value, the operation is irreversible.</p>
</div>
<div class="section" id="s-alterfield">
<span id="alterfield"></span><h3><code class="docutils literal notranslate"><span class="pre">AlterField</span></code><a class="headerlink" href="#alterfield" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AlterField">
<em class="property">class </em><code class="descname">AlterField</code>(<em>model_name</em>, <em>name</em>, <em>field</em>, <em>preserve_default=True</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/fields.html#AlterField"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AlterField" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Alters a field’s definition, including changes to its type,
<a class="reference internal" href="models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a>, <a class="reference internal" href="models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique</span></code></a>,
<a class="reference internal" href="models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_column</span></code></a> and other field attributes.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">preserve_default</span></code> argument indicates whether the field’s default
value is permanent and should be baked into the project state (<code class="docutils literal notranslate"><span class="pre">True</span></code>),
or if it is temporary and just for this migration (<code class="docutils literal notranslate"><span class="pre">False</span></code>) - usually
because the migration is altering a nullable field to a non-nullable one and
needs a default value to put into existing rows. It does not affect the
behavior of setting defaults in the database directly - Django never sets
database defaults and always applies them in the Django ORM code.</p>
<p>Note that not all changes are possible on all databases - for example, you
cannot change a text-type field like <code class="docutils literal notranslate"><span class="pre">models.TextField()</span></code> into a number-type
field like <code class="docutils literal notranslate"><span class="pre">models.IntegerField()</span></code> on most databases.</p>
</div>
<div class="section" id="s-renamefield">
<span id="renamefield"></span><h3><code class="docutils literal notranslate"><span class="pre">RenameField</span></code><a class="headerlink" href="#renamefield" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RenameField">
<em class="property">class </em><code class="descname">RenameField</code>(<em>model_name</em>, <em>old_name</em>, <em>new_name</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/fields.html#RenameField"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RenameField" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Changes a field’s name (and, unless <a class="reference internal" href="models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_column</span></code></a>
is set, its column name).</p>
</div>
<div class="section" id="s-addindex">
<span id="addindex"></span><h3><code class="docutils literal notranslate"><span class="pre">AddIndex</span></code><a class="headerlink" href="#addindex" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.AddIndex">
<em class="property">class </em><code class="descname">AddIndex</code>(<em>model_name</em>, <em>index</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#AddIndex"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.AddIndex" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>Creates an index in the database table for the model with <code class="docutils literal notranslate"><span class="pre">model_name</span></code>.
<code class="docutils literal notranslate"><span class="pre">index</span></code> is an instance of the <a class="reference internal" href="models/indexes.html#django.db.models.Index" title="django.db.models.Index"><code class="xref py py-class docutils literal notranslate"><span class="pre">Index</span></code></a> class.</p>
</div>
<div class="section" id="s-removeindex">
<span id="removeindex"></span><h3><code class="docutils literal notranslate"><span class="pre">RemoveIndex</span></code><a class="headerlink" href="#removeindex" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RemoveIndex">
<em class="property">class </em><code class="descname">RemoveIndex</code>(<em>model_name</em>, <em>name</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/models.html#RemoveIndex"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RemoveIndex" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.11.</span> </div>
<p>Removes the index named <code class="docutils literal notranslate"><span class="pre">name</span></code> from the model with <code class="docutils literal notranslate"><span class="pre">model_name</span></code>.</p>
</div>
</div>
<div class="section" id="s-special-operations">
<span id="special-operations"></span><h2>Special Operations<a class="headerlink" href="#special-operations" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-runsql">
<span id="runsql"></span><h3><code class="docutils literal notranslate"><span class="pre">RunSQL</span></code><a class="headerlink" href="#runsql" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RunSQL">
<em class="property">class </em><code class="descname">RunSQL</code>(<em>sql</em>, <em>reverse_sql=None</em>, <em>state_operations=None</em>, <em>hints=None</em>, <em>elidable=False</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/special.html#RunSQL"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RunSQL" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Allows running of arbitrary SQL on the database - useful for more advanced
features of database backends that Django doesn’t support directly, like
partial indexes.</p>
<p><code class="docutils literal notranslate"><span class="pre">sql</span></code>, and <code class="docutils literal notranslate"><span class="pre">reverse_sql</span></code> if provided, should be strings of SQL to run on
the database. On most database backends (all but PostgreSQL), Django will
split the SQL into individual statements prior to executing them. This
requires installing the <a class="reference external" href="https://pypi.python.org/pypi/sqlparse">sqlparse</a> Python library.</p>
<p>You can also pass a list of strings or 2-tuples. The latter is used for passing
queries and parameters in the same way as <a class="reference internal" href="../topics/db/sql.html#executing-custom-sql"><span class="std std-ref">cursor.execute()</span></a>. These three operations are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">migrations</span><span class="o">.</span><span class="n">RunSQL</span><span class="p">(</span><span class="s2">&quot;INSERT INTO musician (name) VALUES (&#39;Reinhardt&#39;);&quot;</span><span class="p">)</span>
<span class="n">migrations</span><span class="o">.</span><span class="n">RunSQL</span><span class="p">([(</span><span class="s2">&quot;INSERT INTO musician (name) VALUES (&#39;Reinhardt&#39;);&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)])</span>
<span class="n">migrations</span><span class="o">.</span><span class="n">RunSQL</span><span class="p">([(</span><span class="s2">&quot;INSERT INTO musician (name) VALUES (</span><span class="si">%s</span><span class="s2">);&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Reinhardt&#39;</span><span class="p">])])</span>
</pre></div>
</div>
<p>If you want to include literal percent signs in the query, you have to double
them if you are passing parameters.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">reverse_sql</span></code> queries are executed when the migration is unapplied, so
you can reverse the changes done in the forwards queries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">migrations</span><span class="o">.</span><span class="n">RunSQL</span><span class="p">(</span>
    <span class="p">[(</span><span class="s2">&quot;INSERT INTO musician (name) VALUES (</span><span class="si">%s</span><span class="s2">);&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Reinhardt&#39;</span><span class="p">])],</span>
    <span class="p">[(</span><span class="s2">&quot;DELETE FROM musician where name=</span><span class="si">%s</span><span class="s2">;&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Reinhardt&#39;</span><span class="p">])],</span>
<span class="p">)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">state_operations</span></code> argument is so you can supply operations that are
equivalent to the SQL in terms of project state; for example, if you are
manually creating a column, you should pass in a list containing an <code class="docutils literal notranslate"><span class="pre">AddField</span></code>
operation here so that the autodetector still has an up-to-date state of the
model (otherwise, when you next run <code class="docutils literal notranslate"><span class="pre">makemigrations</span></code>, it won’t see any
operation that adds that field and so will try to run it again). For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">migrations</span><span class="o">.</span><span class="n">RunSQL</span><span class="p">(</span>
    <span class="s2">&quot;ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;&quot;</span><span class="p">,</span>
    <span class="n">state_operations</span><span class="o">=</span><span class="p">[</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">AddField</span><span class="p">(</span>
            <span class="s1">&#39;musician&#39;</span><span class="p">,</span>
            <span class="s1">&#39;name&#39;</span><span class="p">,</span>
            <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">),</span>
        <span class="p">),</span>
    <span class="p">],</span>
<span class="p">)</span>
</pre></div>
</div>
<p>The optional <code class="docutils literal notranslate"><span class="pre">hints</span></code> argument will be passed as <code class="docutils literal notranslate"><span class="pre">**hints</span></code> to the
<a class="reference internal" href="../topics/db/multi-db.html#allow_migrate" title="allow_migrate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">allow_migrate()</span></code></a> method of database routers to assist them in making
routing decisions. See <a class="reference internal" href="../topics/db/multi-db.html#topics-db-multi-db-hints"><span class="std std-ref">Hints</span></a> for more details on
database hints.</p>
<p>The optional <code class="docutils literal notranslate"><span class="pre">elidable</span></code> argument determines whether or not the operation will
be removed (elided) when <a class="reference internal" href="../topics/migrations.html#migration-squashing"><span class="std std-ref">squashing migrations</span></a>.</p>
<dl class="attribute">
<dt id="django.db.migrations.operations.RunSQL.noop">
<code class="descclassname">RunSQL.</code><code class="descname">noop</code><a class="headerlink" href="#django.db.migrations.operations.RunSQL.noop" title="Permalink to this definition">¶</a></dt>
<dd><p>Pass the <code class="docutils literal notranslate"><span class="pre">RunSQL.noop</span></code> attribute to <code class="docutils literal notranslate"><span class="pre">sql</span></code> or <code class="docutils literal notranslate"><span class="pre">reverse_sql</span></code> when you
want the operation not to do anything in the given direction. This is
especially useful in making the operation reversible.</p>
</dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.10:</span> <p>The <code class="docutils literal notranslate"><span class="pre">elidable</span></code> argument was added.</p>
</div>
</div>
<div class="section" id="s-runpython">
<span id="runpython"></span><h3><code class="docutils literal notranslate"><span class="pre">RunPython</span></code><a class="headerlink" href="#runpython" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.RunPython">
<em class="property">class </em><code class="descname">RunPython</code>(<em>code</em>, <em>reverse_code=None</em>, <em>atomic=None</em>, <em>hints=None</em>, <em>elidable=False</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/special.html#RunPython"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RunPython" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Runs custom Python code in a historical context. <code class="docutils literal notranslate"><span class="pre">code</span></code> (and <code class="docutils literal notranslate"><span class="pre">reverse_code</span></code>
if supplied) should be callable objects that accept two arguments; the first is
an instance of <code class="docutils literal notranslate"><span class="pre">django.apps.registry.Apps</span></code> containing historical models that
match the operation’s place in the project history, and the second is an
instance of <a class="reference internal" href="schema-editor.html#django.db.backends.base.schema.BaseDatabaseSchemaEditor" title="django.db.backends.base.schema.BaseDatabaseSchemaEditor"><code class="xref py py-class docutils literal notranslate"><span class="pre">SchemaEditor</span></code></a>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">reverse_code</span></code> argument is called when unapplying migrations. This
callable should undo what is done in the <code class="docutils literal notranslate"><span class="pre">code</span></code> callable so that the
migration is reversible.</p>
<p>The optional <code class="docutils literal notranslate"><span class="pre">hints</span></code> argument will be passed as <code class="docutils literal notranslate"><span class="pre">**hints</span></code> to the
<a class="reference internal" href="../topics/db/multi-db.html#allow_migrate" title="allow_migrate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">allow_migrate()</span></code></a> method of database routers to assist them in making a
routing decision. See <a class="reference internal" href="../topics/db/multi-db.html#topics-db-multi-db-hints"><span class="std std-ref">Hints</span></a> for more details on
database hints.</p>
<p>The optional <code class="docutils literal notranslate"><span class="pre">elidable</span></code> argument determines whether or not the operation will
be removed (elided) when <a class="reference internal" href="../topics/migrations.html#migration-squashing"><span class="std std-ref">squashing migrations</span></a>.</p>
<p>You are advised to write the code as a separate function above the <code class="docutils literal notranslate"><span class="pre">Migration</span></code>
class in the migration file, and just pass it to <code class="docutils literal notranslate"><span class="pre">RunPython</span></code>. Here’s an
example of using <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> to create some initial objects on a <code class="docutils literal notranslate"><span class="pre">Country</span></code>
model:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: utf-8 -*-</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">unicode_literals</span>

<span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">migrations</span>

<span class="k">def</span> <span class="nf">forwards_func</span><span class="p">(</span><span class="n">apps</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">):</span>
    <span class="c1"># We get the model from the versioned app registry;</span>
    <span class="c1"># if we directly import it, it&#39;ll be the wrong version</span>
    <span class="n">Country</span> <span class="o">=</span> <span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s2">&quot;myapp&quot;</span><span class="p">,</span> <span class="s2">&quot;Country&quot;</span><span class="p">)</span>
    <span class="n">db_alias</span> <span class="o">=</span> <span class="n">schema_editor</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">alias</span>
    <span class="n">Country</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">using</span><span class="p">(</span><span class="n">db_alias</span><span class="p">)</span><span class="o">.</span><span class="n">bulk_create</span><span class="p">([</span>
        <span class="n">Country</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;USA&quot;</span><span class="p">,</span> <span class="n">code</span><span class="o">=</span><span class="s2">&quot;us&quot;</span><span class="p">),</span>
        <span class="n">Country</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;France&quot;</span><span class="p">,</span> <span class="n">code</span><span class="o">=</span><span class="s2">&quot;fr&quot;</span><span class="p">),</span>
    <span class="p">])</span>

<span class="k">def</span> <span class="nf">reverse_func</span><span class="p">(</span><span class="n">apps</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">):</span>
    <span class="c1"># forwards_func() creates two Country instances,</span>
    <span class="c1"># so reverse_func() should delete them.</span>
    <span class="n">Country</span> <span class="o">=</span> <span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s2">&quot;myapp&quot;</span><span class="p">,</span> <span class="s2">&quot;Country&quot;</span><span class="p">)</span>
    <span class="n">db_alias</span> <span class="o">=</span> <span class="n">schema_editor</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">alias</span>
    <span class="n">Country</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">using</span><span class="p">(</span><span class="n">db_alias</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;USA&quot;</span><span class="p">,</span> <span class="n">code</span><span class="o">=</span><span class="s2">&quot;us&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
    <span class="n">Country</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">using</span><span class="p">(</span><span class="n">db_alias</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;France&quot;</span><span class="p">,</span> <span class="n">code</span><span class="o">=</span><span class="s2">&quot;fr&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span>

    <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">migrations</span><span class="o">.</span><span class="n">RunPython</span><span class="p">(</span><span class="n">forwards_func</span><span class="p">,</span> <span class="n">reverse_func</span><span class="p">),</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>This is generally the operation you would use to create
<a class="reference internal" href="../topics/migrations.html#data-migrations"><span class="std std-ref">data migrations</span></a>, run
custom data updates and alterations, and anything else you need access to an
ORM and/or Python code for.</p>
<p>If you’re upgrading from South, this is basically the South pattern as an
operation - one or two methods for forwards and backwards, with an ORM and
schema operations available. Most of the time, you should be able to translate
the <code class="docutils literal notranslate"><span class="pre">orm.Model</span></code> or <code class="docutils literal notranslate"><span class="pre">orm[&quot;appname&quot;,</span> <span class="pre">&quot;Model&quot;]</span></code> references from South directly
into <code class="docutils literal notranslate"><span class="pre">apps.get_model(&quot;appname&quot;,</span> <span class="pre">&quot;Model&quot;)</span></code> references here and leave most of
the rest of the code unchanged for data migrations. However, <code class="docutils literal notranslate"><span class="pre">apps</span></code> will only
have references to models in the current app unless migrations in other apps
are added to the migration’s dependencies.</p>
<p>Much like <a class="reference internal" href="#django.db.migrations.operations.RunSQL" title="django.db.migrations.operations.RunSQL"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunSQL</span></code></a>, ensure that if you change schema inside here you’re
either doing it outside the scope of the Django model system (e.g. triggers)
or that you use <a class="reference internal" href="#django.db.migrations.operations.SeparateDatabaseAndState" title="django.db.migrations.operations.SeparateDatabaseAndState"><code class="xref py py-class docutils literal notranslate"><span class="pre">SeparateDatabaseAndState</span></code></a> to add in operations that will
reflect your changes to the model state - otherwise, the versioned ORM and
the autodetector will stop working correctly.</p>
<p>By default, <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> will run its contents inside a transaction on
databases that do not support DDL transactions (for example, MySQL and
Oracle). This should be safe, but may cause a crash if you attempt to use
the <code class="docutils literal notranslate"><span class="pre">schema_editor</span></code> provided on these backends; in this case, pass
<code class="docutils literal notranslate"><span class="pre">atomic=False</span></code> to the <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> operation.</p>
<p>On databases that do support DDL transactions (SQLite and PostgreSQL),
<code class="docutils literal notranslate"><span class="pre">RunPython</span></code> operations do not have any transactions automatically added
besides the transactions created for each migration. Thus, on PostgreSQL, for
example, you should avoid combining schema changes and <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> operations
in the same migration or you may hit errors like <code class="docutils literal notranslate"><span class="pre">OperationalError:</span> <span class="pre">cannot</span>
<span class="pre">ALTER</span> <span class="pre">TABLE</span> <span class="pre">&quot;mytable&quot;</span> <span class="pre">because</span> <span class="pre">it</span> <span class="pre">has</span> <span class="pre">pending</span> <span class="pre">trigger</span> <span class="pre">events</span></code>.</p>
<p>If you have a different database and aren’t sure if it supports DDL
transactions, check the <code class="docutils literal notranslate"><span class="pre">django.db.connection.features.can_rollback_ddl</span></code>
attribute.</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> operation is part of a <a class="reference internal" href="../howto/writing-migrations.html#non-atomic-migrations"><span class="std std-ref">non-atomic migration</span></a>, the operation will only be executed in a transaction
if <code class="docutils literal notranslate"><span class="pre">atomic=True</span></code> is passed to the <code class="docutils literal notranslate"><span class="pre">RunPython</span></code> operation.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">RunPython</span></code> does not magically alter the connection of the models for you;
any model methods you call will go to the default database unless you
give them the current database alias (available from
<code class="docutils literal notranslate"><span class="pre">schema_editor.connection.alias</span></code>, where <code class="docutils literal notranslate"><span class="pre">schema_editor</span></code> is the second
argument to your function).</p>
</div>
<dl class="staticmethod">
<dt id="django.db.migrations.operations.RunPython.noop">
<em class="property">static </em><code class="descclassname">RunPython.</code><code class="descname">noop</code>()<a class="reference internal" href="../_modules/django/db/migrations/operations/special.html#RunPython.noop"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.RunPython.noop" title="Permalink to this definition">¶</a></dt>
<dd><p>Pass the <code class="docutils literal notranslate"><span class="pre">RunPython.noop</span></code> method to <code class="docutils literal notranslate"><span class="pre">code</span></code> or <code class="docutils literal notranslate"><span class="pre">reverse_code</span></code> when
you want the operation not to do anything in the given direction. This is
especially useful in making the operation reversible.</p>
</dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.10:</span> <p>The <code class="docutils literal notranslate"><span class="pre">elidable</span></code> argument was added.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.10:</span> <p>The <code class="docutils literal notranslate"><span class="pre">atomic</span></code> argument default was changed to <code class="docutils literal notranslate"><span class="pre">None</span></code>, indicating that
the atomicity is controlled by the <code class="docutils literal notranslate"><span class="pre">atomic</span></code> attribute of the migration.</p>
</div>
</div>
<div class="section" id="s-separatedatabaseandstate">
<span id="separatedatabaseandstate"></span><h3><code class="docutils literal notranslate"><span class="pre">SeparateDatabaseAndState</span></code><a class="headerlink" href="#separatedatabaseandstate" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.migrations.operations.SeparateDatabaseAndState">
<em class="property">class </em><code class="descname">SeparateDatabaseAndState</code>(<em>database_operations=None</em>, <em>state_operations=None</em>)<a class="reference internal" href="../_modules/django/db/migrations/operations/special.html#SeparateDatabaseAndState"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.migrations.operations.SeparateDatabaseAndState" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A highly specialized operation that let you mix and match the database
(schema-changing) and state (autodetector-powering) aspects of operations.</p>
<p>It accepts two list of operations, and when asked to apply state will use the
state list, and when asked to apply changes to the database will use the database
list. Do not use this operation unless you’re very sure you know what you’re doing.</p>
</div>
</div>
<div class="section" id="s-writing-your-own">
<span id="s-writing-your-own-migration-operation"></span><span id="writing-your-own"></span><span id="writing-your-own-migration-operation"></span><h2>Writing your own<a class="headerlink" href="#writing-your-own" title="Permalink to this headline">¶</a></h2>
<p>Operations have a relatively simple API, and they’re designed so that you can
easily write your own to supplement the built-in Django ones. The basic structure
of an <code class="docutils literal notranslate"><span class="pre">Operation</span></code> looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db.migrations.operations.base</span> <span class="k">import</span> <span class="n">Operation</span>

<span class="k">class</span> <span class="nc">MyCustomOperation</span><span class="p">(</span><span class="n">Operation</span><span class="p">):</span>

    <span class="c1"># If this is False, it means that this operation will be ignored by</span>
    <span class="c1"># sqlmigrate; if true, it will be run and the SQL collected for its output.</span>
    <span class="n">reduces_to_sql</span> <span class="o">=</span> <span class="kc">False</span>

    <span class="c1"># If this is False, Django will refuse to reverse past this operation.</span>
    <span class="n">reversible</span> <span class="o">=</span> <span class="kc">False</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span>
        <span class="c1"># Operations are usually instantiated with arguments in migration</span>
        <span class="c1"># files. Store the values of them on self for later use.</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">state_forwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
        <span class="c1"># The Operation should take the &#39;state&#39; parameter (an instance of</span>
        <span class="c1"># django.db.migrations.state.ProjectState) and mutate it to match</span>
        <span class="c1"># any schema changes that have occurred.</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">database_forwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">,</span> <span class="n">from_state</span><span class="p">,</span> <span class="n">to_state</span><span class="p">):</span>
        <span class="c1"># The Operation should use schema_editor to apply any changes it</span>
        <span class="c1"># wants to make to the database.</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">database_backwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">,</span> <span class="n">from_state</span><span class="p">,</span> <span class="n">to_state</span><span class="p">):</span>
        <span class="c1"># If reversible is True, this is called when the operation is reversed.</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">describe</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># This is used to describe what the operation does in console output.</span>
        <span class="k">return</span> <span class="s2">&quot;Custom Operation&quot;</span>
</pre></div>
</div>
<p>You can take this template and work from it, though we suggest looking at the
built-in Django operations in <code class="docutils literal notranslate"><span class="pre">django.db.migrations.operations</span></code> - they’re
easy to read and cover a lot of the example usage of semi-internal aspects
of the migration framework like <code class="docutils literal notranslate"><span class="pre">ProjectState</span></code> and the patterns used to get
historical models, as well as <code class="docutils literal notranslate"><span class="pre">ModelState</span></code> and the patterns used to mutate
historical models in <code class="docutils literal notranslate"><span class="pre">state_forwards()</span></code>.</p>
<p>Some things to note:</p>
<ul>
<li><p class="first">You don’t need to learn too much about <code class="docutils literal notranslate"><span class="pre">ProjectState</span></code> to just write simple
migrations; just know that it has an <code class="docutils literal notranslate"><span class="pre">apps</span></code> property that gives access to
an app registry (which you can then call <code class="docutils literal notranslate"><span class="pre">get_model</span></code> on).</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">database_forwards</span></code> and <code class="docutils literal notranslate"><span class="pre">database_backwards</span></code> both get two states passed
to them; these just represent the difference the <code class="docutils literal notranslate"><span class="pre">state_forwards</span></code> method
would have applied, but are given to you for convenience and speed reasons.</p>
</li>
<li><p class="first">If you want to work with model classes or model instances from the
<code class="docutils literal notranslate"><span class="pre">from_state</span></code> argument in <code class="docutils literal notranslate"><span class="pre">database_forwards()</span></code> or
<code class="docutils literal notranslate"><span class="pre">database_backwards()</span></code>, you must render model states using the
<code class="docutils literal notranslate"><span class="pre">clear_delayed_apps_cache()</span></code> method to make related models available:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">database_forwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">,</span> <span class="n">from_state</span><span class="p">,</span> <span class="n">to_state</span><span class="p">):</span>
    <span class="c1"># This operation should have access to all models. Ensure that all models are</span>
    <span class="c1"># reloaded in case any are delayed.</span>
    <span class="n">from_state</span><span class="o">.</span><span class="n">clear_delayed_apps_cache</span><span class="p">()</span>
    <span class="o">...</span>
</pre></div>
</div>
<div class="versionadded">
<span class="title">New in Django 1.11:</span> <p>This requirement and the <code class="docutils literal notranslate"><span class="pre">clear_delayed_apps_cache()</span></code> method is new.</p>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">to_state</span></code> in the database_backwards method is the <em>older</em> state; that is,
the one that will be the current state once the migration has finished reversing.</p>
</li>
<li><p class="first">You might see implementations of <code class="docutils literal notranslate"><span class="pre">references_model</span></code> on the built-in
operations; this is part of the autodetection code and does not matter for
custom operations.</p>
</li>
</ul>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">For performance reasons, the <a class="reference internal" href="models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> instances in
<code class="docutils literal notranslate"><span class="pre">ModelState.fields</span></code> are reused across migrations. You must never change
the attributes on these instances. If you need to mutate a field in
<code class="docutils literal notranslate"><span class="pre">state_forwards()</span></code>, you must remove the old instance from
<code class="docutils literal notranslate"><span class="pre">ModelState.fields</span></code> and add a new instance in its place. The same is true
for the <a class="reference internal" href="../topics/db/managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> instances in
<code class="docutils literal notranslate"><span class="pre">ModelState.managers</span></code>.</p>
</div>
<p>As a simple example, let’s make an operation that loads PostgreSQL extensions
(which contain some of PostgreSQL’s more exciting features). It’s simple enough;
there’s no model state changes, and all it does is run one command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db.migrations.operations.base</span> <span class="k">import</span> <span class="n">Operation</span>

<span class="k">class</span> <span class="nc">LoadExtension</span><span class="p">(</span><span class="n">Operation</span><span class="p">):</span>

    <span class="n">reversible</span> <span class="o">=</span> <span class="kc">True</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>

    <span class="k">def</span> <span class="nf">state_forwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">database_forwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">,</span> <span class="n">from_state</span><span class="p">,</span> <span class="n">to_state</span><span class="p">):</span>
        <span class="n">schema_editor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;CREATE EXTENSION IF NOT EXISTS </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">database_backwards</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">,</span> <span class="n">from_state</span><span class="p">,</span> <span class="n">to_state</span><span class="p">):</span>
        <span class="n">schema_editor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;DROP EXTENSION </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">describe</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s2">&quot;Creates extension </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Migration Operations</a><ul>
<li><a class="reference internal" href="#schema-operations">Schema Operations</a><ul>
<li><a class="reference internal" href="#createmodel"><code class="docutils literal notranslate"><span class="pre">CreateModel</span></code></a></li>
<li><a class="reference internal" href="#deletemodel"><code class="docutils literal notranslate"><span class="pre">DeleteModel</span></code></a></li>
<li><a class="reference internal" href="#renamemodel"><code class="docutils literal notranslate"><span class="pre">RenameModel</span></code></a></li>
<li><a class="reference internal" href="#altermodeltable"><code class="docutils literal notranslate"><span class="pre">AlterModelTable</span></code></a></li>
<li><a class="reference internal" href="#alteruniquetogether"><code class="docutils literal notranslate"><span class="pre">AlterUniqueTogether</span></code></a></li>
<li><a class="reference internal" href="#alterindextogether"><code class="docutils literal notranslate"><span class="pre">AlterIndexTogether</span></code></a></li>
<li><a class="reference internal" href="#alterorderwithrespectto"><code class="docutils literal notranslate"><span class="pre">AlterOrderWithRespectTo</span></code></a></li>
<li><a class="reference internal" href="#altermodeloptions"><code class="docutils literal notranslate"><span class="pre">AlterModelOptions</span></code></a></li>
<li><a class="reference internal" href="#altermodelmanagers"><code class="docutils literal notranslate"><span class="pre">AlterModelManagers</span></code></a></li>
<li><a class="reference internal" href="#addfield"><code class="docutils literal notranslate"><span class="pre">AddField</span></code></a></li>
<li><a class="reference internal" href="#removefield"><code class="docutils literal notranslate"><span class="pre">RemoveField</span></code></a></li>
<li><a class="reference internal" href="#alterfield"><code class="docutils literal notranslate"><span class="pre">AlterField</span></code></a></li>
<li><a class="reference internal" href="#renamefield"><code class="docutils literal notranslate"><span class="pre">RenameField</span></code></a></li>
<li><a class="reference internal" href="#addindex"><code class="docutils literal notranslate"><span class="pre">AddIndex</span></code></a></li>
<li><a class="reference internal" href="#removeindex"><code class="docutils literal notranslate"><span class="pre">RemoveIndex</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#special-operations">Special Operations</a><ul>
<li><a class="reference internal" href="#runsql"><code class="docutils literal notranslate"><span class="pre">RunSQL</span></code></a></li>
<li><a class="reference internal" href="#runpython"><code class="docutils literal notranslate"><span class="pre">RunPython</span></code></a></li>
<li><a class="reference internal" href="#separatedatabaseandstate"><code class="docutils literal notranslate"><span class="pre">SeparateDatabaseAndState</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-your-own">Writing your own</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="middleware.html"
                        title="previous chapter">Middleware</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="models/index.html"
                        title="next chapter">Models</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/migration-operations.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Jun 03, 2019</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="middleware.html" title="Middleware">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="models/index.html" title="Models">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>